package com.zhixi.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @ClassName GlobalExceptionHandler
 * @Author zhangzhixi
 * @Description 全局异常处理器
 * @Date 2022-7-9 17:39
 * @Version 1.0
 */

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("unknown error");
    }

    /**
     * 自定义业务异常处理器-菜品及套餐分类异常类
     *
     * @param exception 异常对象
     * @return R结果对象
     */
    @ExceptionHandler(CategoryException.class)
    public R<String> exceptionHandler(CategoryException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

    /**
     * 自定义业务异常处理器-菜品及套餐分类异常类
     *
     * @param exception 异常对象
     * @return R结果对象
     */
    @ExceptionHandler(FileNotFoundException.class)
    public R<String> exceptionHandler(FileNotFoundException exception) {
        log.error("菜品管理页面的图片：" + exception.getMessage() + "，没有找到！");
        return R.error("菜品管理页面的图片：" + exception.getMessage() + "，没有找到！");
    }


}

